package com.molichuxing.services.business;


import com.molichuxing.services.infrastructure.dto.request.create.SmsLogCreateDto;
import com.molichuxing.services.infrastructure.service.SmsLogService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.molichuxing.services.business.service.SmsBizService;
import com.molichuxing.services.property.SmsTemplateEnum;
import com.molichuxing.services.util.SmsUtil;

import javax.annotation.Resource;

@Service(value = "smsBizService")
public class SmsBizServiceImpl implements SmsBizService {

	private static final Logger logger = LoggerFactory.getLogger(SmsBizServiceImpl.class);

	@Resource
	private SmsLogService smsLogService;

	/**
	 * 发送短信
	 * @param phoneNumber
	 * @param templateType
	 * @param paramJson
	 * @param signName
	 * @return
	 * @throws ClientException
	 */
    @Override
    public Boolean sendMessage(String phoneNumber, Integer templateType, String paramJson, String signName){
        String templateCode = SmsTemplateEnum.getName(templateType);
        if(StringUtils.isBlank(templateCode)) {
        	return false;
        }
		SendSmsResponse sendSmsResponse = null;


		SmsLogCreateDto dto = new SmsLogCreateDto();
		dto.setPhoneNumber(phoneNumber); //手机号
		dto.setParamJson(paramJson); //参数
		dto.setTemplateCode(templateCode); //短信模板code
		dto.setSignName(signName); //签名
		dto.setSmsType(templateType); //短信类型
		try {
        	sendSmsResponse = SmsUtil.sendMessage(phoneNumber, templateCode, paramJson, signName);
		} catch (Exception e) {
			logger.error("发送短信异常:",e);
			dto.setExceptionState(1);
			dto.setExceptionInformation(e.toString());
			smsLogService.create(dto);
		}
		if (sendSmsResponse != null) {
			dto.setResponseRequestId(sendSmsResponse.getRequestId());
			dto.setResponseBizId(sendSmsResponse.getBizId());
			dto.setResponseCode(sendSmsResponse.getCode());
			dto.setResponseMessage(sendSmsResponse.getMessage());
			try {
				smsLogService.create(dto);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
			return (sendSmsResponse.getCode() != null&&sendSmsResponse.getCode().equals("OK"));
		}

        return false;
    }

    /**
     * 发送语音短信
     * @param phoneNumber
     * @param code 验证码
     * @return
     */
    @Override
    public Boolean sendMessageVoice(String phoneNumber, String code) {
    	try {
    		boolean flag = SmsUtil.sendMessageVoice(phoneNumber, code);
    		return flag;
		} catch (Exception e) {
			logger.error("发送语音短信异常:",e);
			return false;
		}
    }
}
